<script setup lang="ts">
import HomeRequest from '@/request/homeRequest';
import Tools from '@/utils/tools';
import to from '@/utils/to';

interface IProps {
  data: IGoodsAdditionalInfo;
  type: 'video' | 'image';
}

type EmitEvents = {
  (event: 'change', payload: { value: string }): void;
};

const props = defineProps<IProps>();
const emits = defineEmits<EmitEvents>();
const fileList = ref<{ url: string; status?: string; message?: string }[]>([]);

const handleUploadAfterRead = async (event: any) => {
  const { file, index } = event.detail;
  fileList.value = fileList.value.concat({ url: file.url, status: 'uploading', message: '上传中' });
  const fileBase64 = await Tools.uniBase64FromFile(file.url);
  const params = { path: `kics/order/${props.type === 'video' ? 'attr_video' : 'attr_img'}/${new Date().getMonth() + 1}/`, byteFile: fileBase64, type: props.type === 'video' ? 2 : 1 };
  const [err, res] = await to(HomeRequest.UploadFileApi(params));
  if (err) {
    fileList.value[index] = { url: file.url, status: 'failed', message: '上传失败' };
    fileList.value = [...fileList.value];
    return;
  }
  fileList.value[index] = { url: res.data };
  fileList.value = [...fileList.value];
  emits('change', {
    value: fileList.value
      .filter((item) => !item.status)
      .map((item) => item.url)
      .toString(),
  });
};

const handleDeleteMedia = (event: any) => {
  const { index } = event.detail;
  fileList.value.splice(index, 1);
  fileList.value = [...fileList.value];
  emits('change', {
    value: fileList.value
      .filter((item) => !item.status)
      .map((item) => item.url)
      .toString(),
  });
};
</script>

<template>
  <van-cell :title="props.data.attrName" :required="props.data.requiredFlag">
    <view class="text-align-left c-text-12">
      <van-uploader :accept="props.type" :fileList="fileList" :maxCount="props.type === 'video' ? 1 : 9" @afterRead="handleUploadAfterRead" @delete="handleDeleteMedia" />
    </view>
  </van-cell>
</template>
